const db = wx.cloud.database()

const defalutSeat = [
  [1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]

Page({

  /**
   * 页面的初始数据
   */
  data: {
    movieName: '',
    movieId: '',
    date: '',
    price: '',
    cinemaName: '',
    cinemaId: '',
    room: '',
    time: '00:00',
    editFlag: false,
    sessionId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 获取当前小程序的页面栈 
    let pages = getCurrentPages(); 
    // 数组中索引最大的页面--当前页面  
    let currentPage = pages[pages.length-1];
    var options = currentPage.options
    if (typeof(options.id) !== 'undefined') {
      var that = this
      db.collection('session_info').where({
        _id: options.id
      }).get().then(res => {
        that.setData({
          movieName: res.data[0].movieName,
          movieId: res.data[0].movieId,
          cinemaName: res.data[0].cinemaName,
          cinemaId: res.data[0].cinemaId,
          date: res.data[0].date,
          price: res.data[0].price,
          time: res.data[0].startTime,
          room: res.data[0].room,
          editFlag: true,
          sessionId: res.data[0]._id
        })
      })
    } else {
      this.setData({
        movieName: '',
          movieId: '',
          cinemaName: '',
          cinemaId: '',
          date: '',
          price: '',
          startTime: "00:00",
          room: '',
          editFlag: false
      })
    }
  },

  onDisplay() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  formatDate(date) {
    date = new Date(date);
    var month = date.getMonth() + 1
    month = month.toString()
    if (date.getMonth() < 9) {
      month = '0' + month
    }
    
    var day = date.getDate()
    day = day.toString()
    if (date.getDate() < 10) {
      day = '0' + day
    }
    return `${date.getFullYear()}-${month}-${day}`;
  },
  onConfirm(event) {
    this.setData({
      show: false,
      date: this.formatDate(event.detail),
    });
  },

  timeChange(e) {
    this.setData({time: e.detail.value})
    console.log(this.data.time)
  },

  checkTime(date, time) {
    var todayDate = new Date()
    var today = this.formatDate(todayDate)
    if (today != date) {
      return true
    }
    
    var nowTime = todayDate.getHours() + ':' + todayDate.getMinutes()
    if (nowTime < time) {
      return true
    }

    return false
  },

  calculateTime(time, duration) {
    var t = JSON.parse(JSON.stringify(time))
    var splitRes = t.split(':')
    var hour = parseInt(splitRes[0])
    var minute = parseInt(splitRes[1])
    var tot = hour * 60 + minute + duration
    var newHour = parseInt(tot / 60 % 24)
    var newMinute = tot % 60
    var strNewHour = newHour.toString()
    var strNewMinute = newMinute.toString()
    
    if (newHour < 10) {
      strNewHour = '0' + strNewHour
    }

    if (newMinute < 10) {
      strNewMinute = '0' + strNewMinute
    }

    return strNewHour + ':' + strNewMinute
  },

  async onSubmit(e) {
    var that = this
    var movieName = e.detail.value.movieName
    var movieId = e.detail.value.movieId
    var cinemaName = e.detail.value.cinemaName
    var cinemaId = e.detail.value.cinemaId
    var price = parseInt(e.detail.value.price)
    var date = this.data.date
    var room = e.detail.value.room
    if (movieName.length === 0 || movieId.length === 0 || cinemaName === 0 
      || cinemaId === 0 || date.length === 0 || e.detail.value.price.length === 0
      || room.length === 0) {
      wx.showToast({
        title: '请填写内容',
        icon: 'error',
        duration: 1000
      })

      return
    }
    if (price <= 0) {
      wx.showToast({
        title: '请输入正确的价格!',
        icon: 'none',
        duration: 1000
      })

      return
    }

    if (!this.checkTime(date, that.data.time)) {
      wx.showToast({
        title: '请输入正确的时间!',
        icon: 'none',
        duration: 1000
      })

      return
    }

    var duration = 0
    var hasData = true
    await db.collection('movies').where({
      _id: movieId
    }).get().then(res => {
      if (res.data.length === 0) {
        hasData = false
      } else {
        duration = res.data[0].duration
      }
    })
    if (!hasData) {
      wx.showToast({
        title: '影片ID有误',
        icon: 'error',
        duration: 1000
      })

      return
    }

    var endTime = this.calculateTime(this.data.time, duration)

    await db.collection('cinema').where({
      _id: cinemaId
    }).get().then(res => {
      if (res.data.length === 0) {
        hasData = false
      } 
    })

    if (!hasData) {
      wx.showToast({
        title: '影院ID有误',
        icon: 'error',
        duration: 1000
      })

      return
    }

    if (this.data.editFlag) {
      await db.collection('session_info').doc(that.data.sessionId).update({
        data: {
          movieName: movieName,
          movieId: movieId,
          cinemaName: cinemaName,
          cinemaId: cinemaId,
          date: date,
          price: price,
          startTime: that.data.time,
          endTime: endTime,
          room: room
        }
      }).then(res => {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000
        })
      })
      
      return
    }

    await db.collection('session_info').add({
      data: {
        movieName: movieName,
        movieId: movieId,
        cinemaName: cinemaName,
        cinemaId: cinemaId,
        date: date,
        price: price,
        startTime: that.data.time,
        endTime: endTime,
        room: room,
        seat: defalutSeat
      }
    }).then(res => {
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1000
      })
    })
  }
})